// 2025/10/05
// Author: Forever
#include <bits/stdc++.h>
using namespace std;
#define int long long

const int N = 200005;
int t, n, dp[N], v[N], a[N], b[N], pos[N];

class SegmentTree
{
private:
    struct node {
        int ladd, m;
    } tree[(N << 2) + 5];
    void build(int p, int l, int r)
    {
        tree[p].ladd = 0;
        tree[p].m = -1e18;
        if (l == r)
            return;
        int mid = (l + r) >> 1;
        build(p << 1, l, mid);
        build(p << 1 | 1, mid + 1, r);
    }
    void pushdown(int p)
    {
        if (tree[p].ladd != 0) {
            int tag = tree[p].ladd;
            tree[p << 1].ladd += tag, tree[p << 1 | 1].ladd += tag;
            tree[p << 1].m += tag, tree[p << 1 | 1].m += tag;
            tree[p].ladd = 0;
        }
    }
    void add(int p, int l, int r, int ql, int qr, int val)
    {
        if (ql <= l && r <= qr) {
            tree[p].ladd += val, tree[p].m += val;
            return;
        }
        pushdown(p);
        int mid = (l + r) >> 1;
        if (ql <= mid)
            add(p << 1, l, mid, ql, qr, val);
        if (qr > mid)
            add(p << 1 | 1, mid + 1, r, ql, qr, val);
        tree[p].m = max(tree[p << 1].m, tree[p << 1 | 1].m);
    }
    void update(int p, int l, int r, int q, int val)
    {
        if (l == r) {
            tree[p].m = val;
            return;
        }
        pushdown(p);
        int mid = (l + r) >> 1;
        if (q <= mid)
            update(p << 1, l, mid, q, val);
        else
            update(p << 1 | 1, mid + 1, r, q, val);
        tree[p].m = max(tree[p << 1].m, tree[p << 1 | 1].m);
    }
    int query(int p, int l, int r, int ql, int qr)
    {
        if (ql <= l && r <= qr)
            return tree[p].m;
        pushdown(p);
        int mid = (l + r) >> 1;
        int res = -1e18;
        if (ql <= mid)
            res = max(res, query(p << 1, l, mid, ql, qr));
        if (qr > mid)
            res = max(res, query(p << 1 | 1, mid + 1, r, ql, qr));
        return res;
    }
public:
    int n;
    SegmentTree() { }
    void resize(int n) { this->n = n; build(1, 0, n); }
    void add(int ql, int qr, int val) { add(1, 0, n, ql, qr, val); }
    void update(int q, int val) { update(1, 0, n, q, val); }
    int query(int ql, int qr) { return query(1, 0, n, ql, qr); }
};

SegmentTree tree;

void solve()
{
    tree.resize(n);
    tree.update(0, 0);
    for (int i = 1; i <= n; i++) {
        int cur = tree.query(0, pos[a[i]]); 
        tree.add(0, pos[a[i]] - 1, v[a[i]]);
        tree.update(pos[a[i]], cur);
    }
    cout << tree.query(0, n) << endl;
}

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> t;
    while (t--)
    {
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> v[i];
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        for (int i = 1; i <= n; i++)
            cin >> b[i], pos[b[i]] = i;
        memset(dp, 0, sizeof(dp));
        solve();
    }
    return 0;
}